package edu.pku.sei.transformation.atl.adapter;

import java.util.HashMap;
import java.util.Map.Entry;

import edu.pku.sei.transformation.atl.rule.IATLLink;
import edu.pku.sei.transformation.atl.rule.IATLNode;
import edu.pku.sei.transformation.atl.rule.IATLPattern;
import edu.pku.sei.transformation.editor.model.pattern.Pattern;
import edu.pku.sei.transformation.editor.model.variable.ConnectionVariable;
import edu.pku.sei.transformation.editor.model.variable.ObjectVariable;

public class ATLPatternAdapter implements IATLPattern {
	Pattern p = null;
	HashMap<ObjectVariable, IATLNode> nodeMap = new HashMap<ObjectVariable, IATLNode>();

	ATLPatternAdapter(Pattern p) {
		this.p = p;
		for (Object obj : p.getNodes()) {
			if (obj instanceof ObjectVariable) {
				ObjectVariable source = (ObjectVariable) obj;
				IATLNode sourceNode = getNode(source);
				for (Object obj2 : source.getOutgoing()) {
					if (obj2 instanceof ConnectionVariable) {
						ConnectionVariable con = (ConnectionVariable) obj2;
						ObjectVariable target = con.getTarget();
						IATLLink link = new ATLLinkAdapter(con, sourceNode,
								getNode(target));
						sourceNode.getLinks().add(link);
					}
				}

			}
		}
	}

	@Override
	public IATLNode getRoot() {
		for (Object obj : p.getNodes()) {
			if (obj instanceof ObjectVariable) {
				return getNode((ObjectVariable) obj);
			}
		}
		return null;
	}

	private IATLNode getNode(ObjectVariable objVariable) {
		IATLNode node = nodeMap.get(objVariable);
		if (node == null) {
			node = new ATLNodeAdapter(objVariable);
			nodeMap.put(objVariable, node);
		}
		return node;
	}

	protected IATLNode getNode(String name) {
		for (Entry<ObjectVariable, IATLNode> entry : nodeMap.entrySet()) {
			if (entry.getKey().getName().equals(name)) {
				return entry.getValue();
			}
		}
		return null;
	}
}
